package com.tg.app.activity.device.add;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.appbase.custom.config.ApiUrl;
import com.bumptech.glide.Glide;
import com.tange.module.core.wifi.scan.ApScanConfiguration;
import com.tange.module.core.wifi.scan.WiFiScanManager;
import com.tg.app.R;
import com.base.BaseActivity;
import com.tg.app.activity.device.DeviceSettingsActivity;
import com.tg.app.adapter.ApDeviceAdapterEx;
import com.tg.appcommon.android.DialogUtil;
import com.tg.data.bean.DeviceSettingsInfo;
import com.tg.app.helper.ActivityHelper;
import com.tg.app.util.UriUtil;
import com.tange.base.toolkit.StringUtils;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGWifiUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public  class ApSearchDeviceListActivity extends BaseActivity {
    public static final  String TAG ="ApBindHistroyDeviceListActivity";
    private ApDeviceAdapterEx apDeviceAdapter;
    private List<ScanResult> wifiApList = new ArrayList<>();
    private RecyclerView mRecyclerView;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.fragment_ap_device_search_list);
        hideActionBar();
        initView();

        boolean isLocationGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        if (!isLocationGranted) {
            LocationGrantGuideActivity.launch(this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LocationGrantGuideActivity.REQUEST_CODE) {
            if (resultCode == RESULT_CANCELED) {
                finish();
            } else if (resultCode == RESULT_OK) {
                // ignore
            }
        }
    }

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    @Override
    public void onResume() {
        super.onResume();
        WiFiScanManager.scanner().checkWifiEnableAndStartScan(ActivityHelper.getActivityContext(this),
                () -> DialogUtil.openWifi(ApSearchDeviceListActivity.this),
                () -> DialogUtil.openGpsService(ApSearchDeviceListActivity.this));

        getWifiList();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(timeRunable);
        timeRunable = null;
    }

    @Override
    protected void initView() {
        modifyToolBar(R.string.txt_nearby_device);
        findViewById(R.id.tv_scan_no_result).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                DeviceSettingsInfo info = new DeviceSettingsInfo();
                info.deviceID = 0;
                intent.putExtra(DeviceSettingsActivity.EXT_DEVICE_INFO, info);
                UriUtil.openServePlayImpl(ApSearchDeviceListActivity.this, intent, ApiUrl.APP_HELP_DEVICE_NOT_FOUND, "", 0);
            }
        });
        ImageView imageView = findViewById(R.id.iv_auto_track);
        Glide.with(this).asGif().load(R.mipmap.lark).into(imageView);
        mRecyclerView = findViewById(R.id.device_add_ap_camera_list);
        LinearLayoutManager linearLayoutManager =   new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        apDeviceAdapter = new ApDeviceAdapterEx(wifiApList, position -> {
            AddDeviceReportHelper.onEventClickByName(TAG,"item_" + position);
            if (wifiApList.size()>position){
                ScanResult ap = wifiApList.get(position);
                String uuid = ap.SSID;
                if (!StringUtils.isEmpty(uuid) && uuid.startsWith(ApScanConfiguration.INSTANCE.apNamePrefixEndsWithUnderLine())){
                    uuid = uuid.replace(ApScanConfiguration.INSTANCE.apNamePrefixEndsWithUnderLine(), "");
                }
                ActivityHelper.goToBindActivity(ApSearchDeviceListActivity.this, uuid, ScanQrcodeActivity.EXT_FROM_HISTROY);
            }
        });
        mRecyclerView.setAdapter(apDeviceAdapter);
        setClickBack(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddDeviceReportHelper.onEventClickByName(TAG,"back_toolbar");
                finish();
            }
        });
    }


    Handler handler = new Handler();
    Runnable timeRunable = new Runnable() {
        @Override
        public void run() {
            getWifiList();
        }
    };
    private void startTimer() {
        handler.postDelayed(timeRunable, 1000);
    }
    private void getWifiList(){
        WiFiScanManager.scanner().startScan(this);
        List<ScanResult> list = getIPCWifiList(getApplicationContext(), false);
        wifiApList.clear();
        wifiApList.addAll(list);
        mRecyclerView.setVisibility(wifiApList.size() == 0? View.GONE : View.VISIBLE);
        TGLog.d("size = " + wifiApList.size());
        if (wifiApList.size() > 0){
            apDeviceAdapter.notifyDataSetChanged();
        }
        startTimer();
    }

    public static List<ScanResult> getIPCWifiList(Context context, boolean sort) {
        return getWifiList(context, ApScanConfiguration.INSTANCE.apNamePrefixEndsWithUnderLine(), sort);
    }

    public static List<ScanResult> getWifiList(Context context, String startsWith, boolean sort) {
        List<ScanResult> wifiApList = new ArrayList<>();
        List<ScanResult> scanResults = TGWifiUtil.noSameName(TGWifiUtil.getWifiScanResult(context));
        for (ScanResult result : scanResults) {
            TGLog.d("result.SSID = " + result.SSID);
            if (!StringUtils.isEmpty(startsWith)){
                if (!TextUtils.isEmpty(result.SSID) && result.SSID.startsWith(startsWith) && !wifiApList.contains(result)) {
                    wifiApList.add(result);
                }
            }else {
                if (!TextUtils.isEmpty(result.SSID) && !wifiApList.contains(result)) {
                    wifiApList.add(result);
                }
            }

        }
        if (sort) {
            Collections.sort(wifiApList, new Comparator<ScanResult>() {
                @Override
                public int compare(ScanResult o1, ScanResult o2) {
                    return o1.SSID.compareTo(o2.SSID);
                }
            });
        }

        return wifiApList;
    }
}
